package com.hibase.upms.service.login.impl;


import com.hibase.common.exception.HibaseException;
import com.hibase.common.util.UserContext;
import com.hibase.upms.service.login.ILoginService;
import com.hiibase.core.security.cache.Cache;
import com.hiibase.core.security.entity.AccessToken;
import com.hiibase.core.security.entity.UserDetail;
import com.hiibase.core.security.properties.JwtProperties;
import com.hiibase.core.security.provider.JwtProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录service实现
 *
 * @author hufeng
 * @date 2019/04/17
 */
@Service
@Slf4j
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtProvider jwtProvider;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private Cache userCache;

    @Override
    public String checkLoginUser(HttpServletRequest request, String userName, String password) throws HibaseException{
        log.debug("进入login方法");
        // 1 创建UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken usernameAuthentication = new UsernamePasswordAuthenticationToken(userName, password);
        // 2 认证
        Authentication authentication = this.authenticationManager.authenticate(usernameAuthentication);
        // 3 保存认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 4 生成自定义token
        AccessToken accessToken = jwtProvider.createToken((UserDetails) authentication.getPrincipal());

        UserDetail userDetail = (UserDetail) authentication.getPrincipal();
        // 放入缓存
        String authToken = accessToken.getToken().substring(jwtProperties.getTokenPrefix().length());
        userCache.put(authToken,userDetail);
        UserContext.set(userDetail.getUser());
        // 生成token
        return accessToken.getToken();
    }

}
